#include "video.h"

#include "main.h"
#include "flash.h"

#include "FreeRTOS.h"
#include "task.h"
#include "main.h"
#include "cmsis_os.h"
#include "oled.h"
#include "audio.h"

extern SPI_HandleTypeDef hspi2;
extern DMA_HandleTypeDef hdma_spi2_tx;

#define VIDEO_BUFFER_SIZE 1024
struct VIDEO_STRUCT
{
    uint32_t size;
	uint32_t offset;
    uint32_t read_pos;
	uint8_t video_data[2][VIDEO_BUFFER_SIZE];
	uint16_t play_size[2];
	uint8_t video_flag[2];
	uint8_t now_paly_index;
	uint8_t start;
	TimerHandle_t xTimer; 
};

struct VIDEO_STRUCT video_s;

void video_struct_init(struct VIDEO_STRUCT *vs)
{
	vs->video_flag[0] = 0;
	vs->video_flag[1] = 0;
	vs->play_size[0] = 0;
	vs->play_size[1] = 0;
	vs->read_pos = 0;
	vs->size = 0;
	vs->now_paly_index = 0;
}

void video_read_buffer(void)
{
	if(video_s.read_pos < video_s.size)
	{
		for(int i=0;i<2;i++)
		{
			if(video_s.video_flag[i] == 0 && video_s.read_pos < video_s.size)
			{
				
				if(video_s.read_pos + VIDEO_BUFFER_SIZE <= video_s.size)
				{
					SPI_Flash_Read(video_s.video_data[i],video_s.offset + video_s.read_pos,VIDEO_BUFFER_SIZE);
					video_s.play_size[i] = VIDEO_BUFFER_SIZE;
				}
				else{
					SPI_Flash_Read(video_s.video_data[i],video_s.offset + video_s.read_pos,video_s.size - video_s.read_pos);
					video_s.play_size[i] = video_s.size - video_s.read_pos;
				}
				video_s.video_flag[i] = 1;
				video_s.read_pos += video_s.play_size[i];
			}
		}
	}
}

void video_play(uint32_t offset,uint32_t size)
{
	video_struct_init(&video_s);

	video_s.size = size;
	video_s.offset = offset;
	video_read_buffer();
	video_s.now_paly_index = 0;

	if (video_s.xTimer != NULL)
	{
		xTimerStart(video_s.xTimer, 0);
	}
}

static void vTimerCallback(TimerHandle_t xTimer)
{
	uint8_t index = video_s.now_paly_index%2;
	if(video_s.video_flag[index] == 1)
	{
		OLEDDrawAll(video_s.video_data[index], video_s.play_size[index]);
		vTaskSuspendAll();
		video_read_buffer();	
		xTaskResumeAll();  
	}else{
		video_s.size = 0;
		HAL_SPI_DMAStop(&hspi2);
		xTimerStop(video_s.xTimer,portMAX_DELAY);
		//printf("video exit\r\n");
	}
	
}

void StartVideoTimer(void)
{
	video_s.xTimer = xTimerCreate
		("timer",
		 /*定时溢出周期， 单位是任务节拍数*/
		 50,
		 /*是否自动重载， 此处设置周期性执行*/
		 pdTRUE,
		 /*记录定时器溢出次数， 初始化零, 用户自己设置*/
		 (void *)0,
		 /*回调函数*/
		 vTimerCallback);
}

void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi)
{
	if(hspi == &hspi2)
	{
		video_s.video_flag[video_s.now_paly_index%2] = 0;
		video_s.now_paly_index++;
	}
}
